home *** CD-ROM | disk | FTP | other *** search
- Path: news.clark.net!usenet
- From: yom@clark.net (yom)
- Newsgroups: comp.lang.c
- Subject: Re: need psudeo code for binary search
- Date: 1 Mar 1996 01:41:49 GMT
- Organization: home
- Message-ID: <4h5kkt$i31@clarknet.clark.net>
- References: <Pine.SOL.3.91.960229154211.27358B-100000@obelix>
- NNTP-Posting-Host: yom.clark.net
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-Newsreader: WinVN 0.99.7
-
- Here's the actual code I wrote some years ago.
-
- Song (yom@clark.net)
-
- /*
- This function performs a binary search for a key in a sorted table and
- returns the key index value if found. The routine behaves similarly
- to the standard library bsearch function except for added capabilities
- of convergence and directional search.
- */
-
- #include <string.h>
-
- #define GE 1
- #define EQ 0
- #define LE -1
- #define NOTFOUND -1
-
- int binsearch (void *key,int ksize,void *base,int nel,int bsize,int mode,
- int (*compare)(void *,void *))
- {
- int jl = 0;
- int ju = nel - 1;
- int jm;
- int diff = 1;
- int idx = NOTFOUND;
- int tidx;
- void *bl = (char *) base;
- void *bu = (char *) base + (ju * bsize);
-
- /*
- Calculate the key index value. If the input key value is within the
- range of base, conduct bisection method search. Otherwise, set the
- key index value to minimum or maximum value of base depending on the
- mode.
- */
-
- if (compare(key,bl) >= 0 && compare(key,bu) <= 0)
- {
- while (diff && ju >= jl)
- {
- jm = (ju + jl) / 2;
- diff = compare(key,(char *) base + (jm * bsize));
- if (diff > 0)
- jl = jm + 1;
- else if (diff < 0)
- ju = jm - 1;
- }
- if (!diff)
- idx = jm;
- else if (mode == GE)
- idx = diff < 0 ? jm : jm + 1;
- else if (mode == LE)
- idx = diff > 0 ? jm : jm - 1;
- }
- else if (mode == GE && compare(key,bl) < 0)
- idx = jl;
- else if (mode == LE && compare(key,bu) > 0)
- idx = ju;
-
- /*
- Update the key value and converge via recursion if necessary.
- */
-
- if (idx != NOTFOUND)
- {
- if (diff)
- memcpy(key,(char *) base + (idx * bsize),ksize);
- if (idx > 0)
- {
- tidx = binsearch(key,ksize,base,idx,bsize,EQ,compare);
- if (tidx != NOTFOUND)
- idx = tidx;
- }
- }
-
- return idx;
- }
-
-
-
- In article <Pine.SOL.3.91.960229154211.27358B-100000@obelix>,
- brown1@gaul.csd.uwo.ca says...
- >
- >
- >Does any one have some psudeocode /code (C) for a binary search using
- >arrays of chars.
- >
- >any sugesstions on book or file locations would be appriciated.
- >
- >
- >If possible could anyopne who can help out mail me the info.
- >
- >brown1@gaul.csd.uwo.ca
- >
- >
- >thanks in advance.
- >
- >chris
- >
- >
-
-